package cn.schoolwow.quickdao.module.database.ddl.query.service.entity;

import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.module.database.ddl.common.flow.SetHasResultSetFlow;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.Arrays;

public class HasTableFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        String tableName = flowContext.checkData("tableName", String.class);

        flowContext.putTemporaryData("name", "判断表是否存在");
        switch (databaseType){
            case H2:{
                tableName = tableName.toUpperCase();
                flowContext.putTemporaryData("sql", "select table_name from information_schema.tables where table_name = ?;");
            }break;
            case SQLite:{
                flowContext.putTemporaryData("sql", "select name from sqlite_master where type = 'table' and name = ?;");
            }break;
            case Mysql:
            case MariaDB:{
                flowContext.putTemporaryData("sql", "show tables like ?;");
            }break;
            case Postgresql:{
                flowContext.putTemporaryData("sql", "select tablename from pg_tables where schemaname = 'public' and tablename = ?;");
            }break;
            case SQLServer:{
                flowContext.putTemporaryData("sql", "select name from sysobjects where xtype='u' and name = ?;");
            }break;
            case Oracle:{
                flowContext.putTemporaryData("sql", "select table_name from user_tables where table_name = ?");
            }break;
        }
        flowContext.putTemporaryData("parameters", Arrays.asList(tableName));
        flowContext.executeFlowList(new SetHasResultSetFlow(), new ExecuteQueryConnectionFlow());
        boolean hasResult = flowContext.checkData("hasResult", boolean.class);
        if(!hasResult){
            flowContext.broken("表不存在!表名:"+tableName);
        }
        flowContext.putReturnData("hasResult", hasResult);
    }

    @Override
    public String name() {
        return "表是否存在";
    }
}
